package com.lw.common.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log

/**
 * @description: 全局异常捕获
 * @author: yuan
 * @date: 2023/3/2/0002
 */
class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {
    private var mContext: Context? = null
    private var defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null

    /* 初始化 */
    fun init(context: Context?) {
        mContext = context
        Thread.setDefaultUncaughtExceptionHandler(this)
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
    }

    override fun uncaughtException(thread: Thread, ex: Throwable) {
        if (isHandler(ex)) {
            handlerException(ex)
        } else {
            defaultUncaughtExceptionHandler!!.uncaughtException(thread, ex)
        }
    }

    private fun isHandler(ex: Throwable?): Boolean {
        // 排序不需要捕获的情况
        return ex != null

        // ...
    }

    private fun handlerException(ex: Throwable) {
        val brand = Build.BRAND // android系统定制商
        val model = Build.MODEL // 版本
        Log.d("handlerException", "设备型号：" + brand + "-" + model + "；崩溃原因：" + ex.message)
    }

    companion object {
        private val lock = Any()

        @SuppressLint("StaticFieldLeak")
        private var mCrashHandler: CrashHandler? = null
        val instance: CrashHandler?
            get() {
                synchronized(lock) {
                    if (mCrashHandler == null) {
                        synchronized(lock) {
                            if (mCrashHandler == null) {
                                mCrashHandler = CrashHandler()
                            }
                        }
                    }
                    return mCrashHandler
                }
            }
    }
}